package com.edz.from0507to0513apk.NettyAndroid;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.edz.from0507to0513apk.Base.BaseActivity;
import com.edz.from0507to0513apk.R;

import java.net.InetSocketAddress;

import butterknife.BindView;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 使用Netty与后台保持tcp长连接
 */
public class NettyAndroidClientActivity extends BaseActivity {
    @BindView(R.id.et_ip)
    EditText et_ip;
    @BindView(R.id.et_port)
    EditText et_port;
    @BindView(R.id.btn_connect)
    Button btn_connect;
    @BindView(R.id.btn_send)
    Button btn_send;

    private NioEventLoopGroup group;
    private Channel mChannel;
    private ChannelFuture cf;

    public static int MSG_REC = 0xabc;

    public static int PORT = 8899;
    public static final String HOST = "192.168.0.34";

    private static Context context;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_REC) {
                Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void setEvent() {
        context = this;

        btn_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                connected();
                NettyClient.getInstance().connect();
//                NettyClient.getInstance().init();
            }
        });

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
//                NettyClient.getInstance().init();
            }
        });
    }

    private void sendMessage() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.i("send", "mChannel.write sth & " + mChannel.isOpen());
                    mChannel.writeAndFlush("hello,中文.\r\n");
                    mChannel.read();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // 连接到Socket服务端
    private void connected() {
        new Thread() {
            @Override
            public void run() {
                group = new NioEventLoopGroup();
                try {
                    // Client服务启动器 3.x的ClientBootstrap
                    // 改为Bootstrap，且构造函数变化很大，这里用无参构造。
                    Bootstrap bootstrap = new Bootstrap();
                    // 指定EventLoopGroup
                    bootstrap.group(group);
                    // 指定channel类型
                    bootstrap.channel(NioSocketChannel.class);
                    // 指定Handler
                    bootstrap.handler(new MyClientInitializer(context, mHandler));
                    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
                    bootstrap.option(ChannelOption.TCP_NODELAY, true);
                    bootstrap.option(ChannelOption.SO_TIMEOUT, 5000);
                    // 连接到本地的7878端口的服务端
                    cf = bootstrap.connect(new InetSocketAddress(HOST, PORT));
                    mChannel = cf.sync().channel();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_netty_android_client;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (group != null) {
            group.shutdownGracefully();
        }
    }
}
